﻿/// <reference path="backbone-min.js" />
/// <reference path="jquery-1.8.2.min.js" />
/// <reference path="underscore-min.js" />
/// <reference path="modelsmanager.js" />

'use strict';

var context = SP.ClientContext.get_current();

var ezEditViewString = "ezEditView";
var viewedListsString = "viewedLists";
var footerString = "FooterView";
var configurationListName = "Configuration";
var chartTypeFieldName = "ChartType";
var chartConfigurationFieldName = "Configuration";
var viewedLists = {}; 

var App = {
    Template: {},
    //view
    MainView: {},
    ChartTypesView: {},
    ConfigurationView: {},
    ErrorInEzEditView: {},
    ErrorInChartView: {},
    Views:[],

    AppRouter: {},
    ViewedLists: {},
    ChartTypes: {},
    ChartType:{},
    ConfigurationSettings: {},
    Chart : {},
    
    ChartConfiguration: {},

    ErrorMessage: null,

    user: context.get_web().get_currentUser()
};

// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
   // createChart();
    App.ChartConfiguration = new ChartConfigurationModel();
    App.HeaderView = new HeaderView();
    App.HeaderView.render();
    
    App.EzEditView = new EzEditView();
    App.MainView = new MainView();
    App.ErrorInEzEditView = new ErrorInEzEditView();

    App.ViewedListsView = new ViewedListsView();
    App.ChartTypesView = new ChartTypeView();

    App.ViewedLists = new ViewedListsModels();
    viewedLists = new ViewedListsModels();
    App.ConfigurationSettings = new ConfigurationModel();
    
    App.ConfigurationView = new ChartConfigurationView();
    App.ErrorInChartView = new ErrorInChartView();

    getUserName();

    App.AppRouter = new AppRouter();
});

App.createChart = function()
{
    App.Chart = null;
    App.Chart = new ChartModel();
    App.Chart.seriesDefaults.type = App.ChartType.chartType;
    var site = context.get_site();
    var web = site.get_rootWeb();
    context.load(web);
    var targetList = web.get_lists().getByTitle(App.ViewedLists.at(0).get('listName'));
    context.load(targetList);
    var query = SP.CamlQuery.createAllItemsQuery();

    var listItems = targetList.getItems(query);
    context.load(listItems);

    context.executeQueryAsync(function (sender, e) {
        var itemEnumerator = listItems.getEnumerator();
        var xFieldName = App.ConfigurationSettings.xAxis.filedName;
        var yAxis = App.ConfigurationSettings.yAxis;
        var index = 0;
        while (itemEnumerator.moveNext()) {
            var item = itemEnumerator.get_current();
            if ($.inArray(item.get_item(xFieldName), App.Chart.categoryAxis.categories) == -1) {
                App.Chart.categoryAxis.categories.push(item.get_item(xFieldName));
            }
            for (var i = 0; i < App.Chart.categoryAxis.categories.length; i++)
            {
                if (item.get_item(xFieldName) == App.Chart.categoryAxis.categories[i]) {
                    
                    if (App.ConfigurationSettings.yAxis.aggregateFunction[index] == 'Sum') {
                        try
                        {
                            for (var yAxisIndex = 0; yAxisIndex < App.ConfigurationSettings.yAxis.fieldNames.length; yAxisIndex++) {
                                if (App.Chart.series[yAxisIndex]) {
                                    App.Chart.series[yAxisIndex].name = yAxis.seriesName[yAxisIndex];
                                    if (App.Chart.series[yAxisIndex].data[i]) {
                                        App.Chart.series[yAxisIndex].data[i] += parseInt(item.get_item(yAxis.fieldNames[yAxisIndex]));
                                    }
                                    else {
                                        App.Chart.series[yAxisIndex].data.push(parseInt(item.get_item(yAxis.fieldNames[yAxisIndex])));
                                    }
                                }
                                else {
                                    App.Chart.series.push({ name:item.get_item(yAxis.fieldNames[yAxisIndex]), data: [parseInt(item.get_item(yAxis.fieldNames[yAxisIndex]))] });
                                }
                            }
                        }
                        catch (e) {
                           
                        }
                    }
                }
            }
        }

        createChart();
    });
}

App.processData = function (listItems)
{
    
}


App.isReady = function () {
    if (App.ViewedLists.length == 0) {
        App.ErrorMessage = 'You must select the List first in ezEdit, you can click ezEdit on the top right and select the Viewed Lists settings to choice your lists.';
        return false;
    }
    if (!App.ChartType) {
        App.ErrorMessage = 'You must select the Chart type first in ezEdit, you can click ezEdit on the top right and select the Chart Type settings to choice the Type.';
        return false;
    }
    if ((!App.ConfigurationSettings ||
        !App.ConfigurationSettings.xAxis ||
        !App.ConfigurationSettings.xAxis.filedName)
        ||
        (!App.ConfigurationSettings.yAxis ||
        !App.ConfigurationSettings.yAxis.fieldNames ||
        !App.ConfigurationSettings.yAxis.fieldNames.length ||
        App.ConfigurationSettings.yAxis.fieldNames.length == 0 ||
        !App.ConfigurationSettings.yAxis.aggregateFunction ||
        !App.ConfigurationSettings.yAxis.aggregateFunction.length ||
        App.ConfigurationSettings.yAxis.aggregateFunction.length == 0 ||
        !App.ConfigurationSettings.yAxis.seriesName ||
        !App.ConfigurationSettings.yAxis.seriesName.length ||
        App.ConfigurationSettings.yAxis.seriesName.length == 0)) {
        App.ErrorMessage = 'You must configure the Chart first in ezEdit, you can click ezEdit on the top right and select the Configuration settings to configure the Chart.';
        return false;
    }
    return true;
}

App.ensureData = function (onSuccess)
{
    App.getConfigurationSettings(function (item) {
        if (item) {
            var viewedList = item.get_item('ViewedLists');
            var lists = JSON.parse(viewedList);
            var isRunSuccess = false;
            App.ViewedLists.clear();
            if (lists) {
                //App.ViewedLists.clear();
                //viewed lists
                for (var i = 0; i < lists.length; i++) {
                    var viewedListModel = new ViewedListsModel();
                    viewedListModel.set({ siteUrl: lists[i].siteUrl });
                    viewedListModel.set({ listName: lists[i].listName });
                    viewedListModel.set({ selected: true });
                    viewedListModel.set({ description: lists[i].description });
                    viewedListModel.set({ itemCount: lists[i].itemCount });
                    viewedListModel.set({ imageUrl: lists[i].imageUrl });
                    App.ViewedLists.add(viewedListModel);

                }
                //chart type
                var ct = item.get_item(chartTypeFieldName);
                var chartType = JSON.parse(ct);
                App.ChartType = new ChartTypesModel();
                if (chartType && chartType.length && chartType.length > 0) {
                    App.ChartType = chartType[0];
                }

                //xAxis and yAxis
                var configuration = item.get_item(chartConfigurationFieldName);
                var configurationObj = JSON.parse(configuration);
                if (configurationObj) {
                    if (configurationObj.xAxis) {
                        App.ConfigurationSettings.xAxis.filedName = configurationObj.xAxis.filedName;
                        App.ConfigurationSettings.xAxis.sortName = configurationObj.xAxis.sortName;
                        App.ConfigurationSettings.set({ xAxis: App.ConfigurationSettings.xAxis });
                    }
                    if (configurationObj.yAxis) {
                        for (var i = 0; i < configurationObj.yAxis.fieldNames.length; i++) {
                            App.ConfigurationSettings.yAxis.fieldNames[i] = configurationObj.yAxis.fieldNames[i];
                            App.ConfigurationSettings.yAxis.aggregateFunction[i] = configurationObj.yAxis.aggregateFunction[i];
                            App.ConfigurationSettings.yAxis.seriesName[i] = configurationObj.yAxis.seriesName[i];
                        }
                        App.ConfigurationSettings.set({ yAxis: App.ConfigurationSettings.yAxis });
                    }
                }
                //if (!isRunSuccess && onSuccess) {
                //    onSuccess();
                //    isCreated = true;
                //}
            }
            if (!App.isReady()) {
                App.ErrorInChartView.render();
            }
            else {
                if (!isRunSuccess && onSuccess) {
                    onSuccess();
                }
            }
        }
    });
}

App.getConfigurationSettings = function (onSuccess, onFail)
{
    var query = new SP.CamlQuery();
    var web = context.get_web();
    var configurationList = web.get_lists().getByTitle(configurationListName);
    var items = configurationList.getItems(query);
    context.load(items);
    context.executeQueryAsync(function (senader, e) {
        var item = items.get_item(0);
        if (item) {
            if (onSuccess) {
                onSuccess(item);
            }
        }
        else {
            if (onFail) {
                onFail();
            }
        }
    }, onFail);
}

// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    context.load(App.user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#user').text(App.user.get_title());
}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}


function createChart() {
   
    
    var chart = $("#content").data("kendoChart");
    if (chart) {
        updateChartMetadata(App.Chart, chart);
        chart.redraw();
    }
    else {
        $("#content").kendoChart(
        chartMetadata(App.Chart)
    );
    }
}

function chartMetadata(chartModel)
{
    return {
        title: {
            text: chartModel.title.text
        },
        legend: {
            position: "bottom"
        },
        seriesDefaults: {
            type: chartModel.seriesDefaults.type
        },
        series: chartModel.series,
        valueAxis: {
            line: {
                visible: false
            }
        },
        categoryAxis: {
            categories: App.Chart.categoryAxis.categories,
            majorGridLines: {
                visible: false
            }
        }
    };
}

function updateChartMetadata(chartModel, newChartModel)
{
    newChartModel.options.title.text = chartModel.title.text
    newChartModel.options.legend.position = chartModel.legend.position;
    newChartModel.options.series = chartModel.series;
    var length = newChartModel.options.series.length;
    for (var i = 0; i < length; i++) {
        newChartModel.options.series[i].type = chartModel.seriesDefaults.type;
    }
    newChartModel.options.valueAxis.line.visible = false;
    newChartModel.options.categoryAxis.categories = App.Chart.categoryAxis.categories;
    newChartModel.options.categoryAxis.majorGridLines.visible = false;
}

